package edu.zhku.web4.util;

import java.io.*;
import java.sql.*;
import java.util.Properties;

public class JdbcUtil {

    /**
     * 建立连接
     */
    public static Connection getConnection() {
        Connection conn = null;
        Properties pros = new Properties();
        try {
            pros.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties"));
            Class.forName(pros.getProperty("jdbc.driver"));
            String url = pros.getProperty("jdbc.url");
            String username = pros.getProperty("jdbc.username");
            String password = pros.getProperty("jdbc.password");
            conn = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return conn;
    }

    /**
     * 关闭连接
     */
    public static void closeAll(Connection conn, Statement stm, ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (stm != null) {
            try {
                stm.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 封装增删改
     */
    public static int executeUpdate(String sql, Object... args) {
        int num = 0;
        Connection conn = null;
        PreparedStatement pstm = null;
        try {
            conn = getConnection();
            pstm = conn.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
                pstm.setObject(i + 1, args[i]);
            }
            num = pstm.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeAll(conn, pstm, null);
        }
        return num;
    }
}
